#!/bin/bash

####################################
# this module defines all action about config
####################################

dotfiles_config_root="${HOME}/.config/dotfiles-configs"
proxy_config_path="${dotfiles_config_root}/dfproxym.json"

# store loading config as map
declare -A CFG # 全局数组
CFG=()

get_default_json_config() {
  cat <<EOF
{
  // docker proxy config
  "docker": {
    
    // docker image proxy prefix
    "proxy_prefix": "",
    
    // retag after pulling from proxy
    "retag_after_pull_from_proxy": 1,
    
    // if keep proxy image tag after pulling
    "keep_proxy_tag": 0,
    
    // mirror docker url
    "mirror_url": "",
    
    // the api call command used to get proxy list
    "api_cmd": "curl --silent https://api.suoyinmulu.com/open/v1/docker-hub/seeded-up/lists",

    // if show list api call response
    "api_show_response": 0,

    // cmd which is used to extract proxy list from api reponse json
    "extract_cmd": "jq -r '.data.list[]'"
  },

  // git proxy config
  "git": {
    // NOTE: the instead only affects 'git clone' and 'git pull'
    "insteads": [
      {
        "from": "https://github.com/",
        "to": "https://ghproxy.com/https://github.com/"
      }
    ]
  }
}
EOF
}

config_usage() {
  echo "Kind:  config"
  echo "  e.g. $prog config                              note: show config subcommand usage"
  echo "       $prog config init                         note: init proxy config"
  echo "       $prog config list                         note: list proxy config"
  echo "       $prog config edit                         note: edit proxy config, init config first if config does not exist"
}

# load_properties_configs() {
#   check_config_if_exist
#   eval "$(sed -E 's/^[[:space:]]*#.*$//;/^[[:space:]]*$/d;s/^[[:space:]]*//;s/[[:space:]]*=[[:space:]]*/=/' ${proxy_config_path})"
# }

#######################
# load json config
# after load the configs, you can use {cfg[db.host]} to get any attr in config
#######################
load_configs() {
  check_config_if_exist

  while IFS='▸' read -r k v; do
    CFG[$k]=$v
    # _info "$k $v"
  done < <(
    strip_jsonc "${proxy_config_path}" |
      jq -r '
        paths(scalars) as $p
        | [ ($p | map(tostring) | join(".")), (getpath($p)) ]
        | join("▸")
    '
  )

}

list_configs() {
  if [ ! -f "${proxy_config_path}" ]; then
    _err "${proxy_config_path} does not exist, please init by '$prog config init' "
  fi
  cat "$proxy_config_path"
}

check_config_if_exist() {
  if [ ! -f "${proxy_config_path}" ]; then
    _err "${proxy_config_path} does not exist, please init by '$prog config init' "
  fi
}

###########################
# get keys match regex from CFG
# @param m_dict: source dict
# @param regex_str: regex string
# @return keys
###########################
get_keys_grep_regex_from_cfg() {
  local regex_string=${1:-""}
  local -a hits
  for k in "${!CFG[@]}"; do
    [[ $k =~ $regex_string ]] && hits+=("$k")
  done
  printf '%s\n' "${hits[@]}" | sort -u
}

execute_subcmd_config() {
  local cmd=${1:-""}

  case "${cmd}" in
  init)
    if [ -f "${proxy_config_path}" ]; then
      _info "${proxy_config_path} has existed, skip init"
      exit 0
    fi
    mkdir -p "$(dirname ${proxy_config_path})"
    get_default_json_config >"${proxy_config_path}"
    _info "create proxy config: ${proxy_config_path}, you can execute '${prog} config' for getting more info."
    ;;
  list)
    load_configs
    list_configs
    ;;
  edit)
    if [ ! -f "$proxy_config_path" ]; then
      _info "proxy config: ${proxy_config_path} has not existed, init now..."
      mkdir -p "$(dirname ${proxy_config_path})"
      get_default_json_config >"${proxy_config_path}"
    fi
    "${default_editor}" "${proxy_config_path}"
    ;;
  *)
    config_usage
    _err "unknown subcmd of config: ${cmd}"
    ;;
  esac
}
